﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using MessageHandling;
using System.Xml.Linq;
using System.Xml;

namespace TcpTestClient
{
    class TcpTestClient
    {
        
        
        void messageCallback(ReadMessageEventArgs state)
        {
            this.state = state;
        }

        public  void sendMessageToServer(string address,int port)
            {
                bool flag = false;
            TcpClient client = new TcpClient(address, port);
            ReadMessageAsyncCallback cb = new ReadMessageAsyncCallback(messageCallback);
                try
                {
                    //Stream s = client.GetStream();
                    while (true)
                    {
                        ReadMessageAsync async_msg = new ReadMessageAsync(client.Client, cb);
                        while (state == null)
                            System.Threading.Thread.Sleep(500);
                        if (state.Error != null)
                            throw state.Error;
                        if (state.IsKeepAliveMessage)
                        {
                            Console.WriteLine();
                            Console.WriteLine("Keep alive message received");
                            state = null;
                            continue;
                        }
                        XElement input_message = MessageBuilder.ConvertByteArrayToXml(state.Message);
                        Console.Write(input_message.ToString());
                        state = null;

                        FileStream fileStream = new FileStream(@"../../SampleReply.xml", FileMode.Open, FileAccess.Read);
                        XmlReader reader_xml = XmlReader.Create(fileStream);
                        XElement reply = XElement.Load(reader_xml);

                        byte[] message_bytes = MessageBuilder.ConvertXmlToByteArray(reply, System.Text.Encoding.UTF8);
                        message_bytes = MessageBuilder.WrapMessage(message_bytes);
                        if (flag)
                        {
                            flag = false;
                       //     System.Threading.Thread.Sleep(2000);
                        }
                        else
                            flag = true;
                        client.Client.Send(message_bytes);
                    }

    
                }
                finally
                {
                   
                    client.Close();
                }
            }

        ReadMessageEventArgs state = null;
      
    }
}
